import { useState, useContext, useEffect, useCallback, useRef } from "react";
import { AuthContextType } from "@/App";
import api, { ApiResponse } from "@/services/api";
import { AuthContext } from "@/App";
import { useParams, useNavigate } from "react-router-dom";
import { cn } from "@/lib/utils";
import { useTheme } from "@/hooks/useTheme";
import { motion } from "framer-motion";
import { toast } from "sonner";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import { MilkdownPreview, fontOptions } from "@/components/MilkdownPreview";
import EditorModal from "@/components/EditorModal";
import { showConfirm } from "@/lib/dialog";
import ExportModal from '@/components/ExportModal';
import DirectorySelectModal from '@/components/DirectorySelectModal';
import { ExportType } from '@/lib/export-types';
import PostmanImportModal from '@/components/PostmanImportModal';
import VersionHistoryModal from '@/components/VersionHistoryModal';
import ShareModal from '@/components/ShareModal';

interface DocumentNode {
  id: string;
  name: string;
  type: 'folder' | 'file';
  children?: DocumentNode[];
  content?: string;
  isExpanded?: boolean;
  hasChild?: boolean;
  createUser?: string;
  createTime?: string;
  updateUser?: string;
  updateTime?: string;
}

interface DirectoryItem {
  id: string;
  name: string;
  pid: string;
  hasChild: boolean;
}

interface DocumentItem {
  docId: string;
  docTitle: string;
}

export default function ProjectDetail() {
  const { 
    isAuthenticated, 
    userInfo, 
    logout, 
    currentTeam,
    saveProjectContext,
    currentProjectType,
    currentProjectPermission
  } = useContext(AuthContext) as AuthContextType;
  const [showFolderNameModal, setShowFolderNameModal] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [newFolderParentId, setNewFolderParentId] = useState('root');
  const navigate = useNavigate();
  const { theme, toggleTheme, isDark } = useTheme();
  const [documents, setDocuments] = useState<DocumentNode[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const previewRef = useRef<HTMLDivElement>(null);
  const leftPanelRef = useRef<HTMLDivElement>(null);
  const rightPanelRef = useRef<HTMLDivElement>(null);
  const [showEditorModal, setShowEditorModal] = useState(false);
  const [editorContent, setEditorContent] = useState('');
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);
  const [currentEditingDocId, setCurrentEditingDocId] = useState('');
  const [selectedFont, setSelectedFont] = useState('inter');
  const [contextMenu, setContextMenu] = useState<{
    visible: boolean;
    x: number;
    y: number;
    type: 'folder' | 'file';
    nodeId: string;
    nodeName: string;
  }>({
    visible: false,
    x: 0,
    y: 0,
    type: 'folder',
    nodeId: '',
    nodeName: ''
  });
  const [hoveredNodeId, setHoveredNodeId] = useState<string>('');
  const [showExportModal, setShowExportModal] = useState(false);
  const [exportType, setExportType] = useState<ExportType>(ExportType.SINGLE);
  const [exportDocId, setExportDocId] = useState<string>('');
  const [exportDirectoryId, setExportDirectoryId] = useState<string>('');
  const [exportDirectoryName, setExportDirectoryName] = useState<string>('');
  const [projectName, setProjectName] = useState<string>('');
  const [showDirectorySelectModal, setShowDirectorySelectModal] = useState(false);
  const [showMoreMenu, setShowMoreMenu] = useState(false);
  const [showPostmanImportModal, setShowPostmanImportModal] = useState(false);
  const [authCheckComplete, setAuthCheckComplete] = useState(false);
  const [showVersionHistoryModal, setShowVersionHistoryModal] = useState(false);
  const [currentVersionDocId, setCurrentVersionDocId] = useState('');
  // 新增重命名弹窗状态
  const [showRenameModal, setShowRenameModal] = useState(false);
  const [renameTarget, setRenameTarget] = useState<{ type: 'folder' | 'file'; id: string; oldName: string }>({ type: 'file', id: '', oldName: '' });
  const [renameValue, setRenameValue] = useState('');
  const [isRenaming, setIsRenaming] = useState(false);
  // 新增分享弹窗状态
  const [showShareModal, setShowShareModal] = useState(false);
  const [shareType, setShareType] = useState<'project' | 'doc'>('project');
  const [shareId, setShareId] = useState('');
  const [shareTitle, setShareTitle] = useState('');
  const newDocIdRef = useRef<string | null>(null);

  // 只从 context 或 localStorage 获取团队ID、项目ID、项目名称
  const teamId = currentTeam || localStorage.getItem('currentTeam') || '';
  const projectId = localStorage.getItem('currentProject') || '';

  // 权限相关
  const [projectType, setProjectType] = useState<string>(() => currentProjectType || localStorage.getItem('currentProjectType') || '');
  const [projectPermission, setProjectPermission] = useState<string>(() => currentProjectPermission || localStorage.getItem('currentProjectPermission') || '');
  useEffect(() => {
    setProjectType(currentProjectType || localStorage.getItem('currentProjectType') || '');
    setProjectPermission(currentProjectPermission || localStorage.getItem('currentProjectPermission') || '');
  }, [currentProjectType, currentProjectPermission]);

  // 权限判断函数
  const isOwner = projectType === 'OWNER';
  const isRW = projectPermission === 'rw';
  const isReadOnly = projectType === 'PARTICIPANT' && projectPermission === 'r';

  // 认证检查：等待认证状态确定后再进行跳转
  useEffect(() => {
    // 减少延迟时间，提高响应速度
    const timer = setTimeout(() => {
      setAuthCheckComplete(true);
      if (!isAuthenticated) {
        console.log('认证检查完成，用户未登录，跳转到登录页面');
        navigate('/login');
        return;
      }
    }, 300); // 减少到300ms，提高响应速度

    return () => clearTimeout(timer);
  }, [isAuthenticated, navigate]);

  // 团队ID验证：如果teamId无效则跳转到团队页面
  useEffect(() => {
    if (authCheckComplete && isAuthenticated && (!teamId || teamId === 'null' || teamId === 'undefined')) {
      toast.error('团队ID无效，请重新选择团队');
      navigate('/team-list');
      return;
    }
  }, [authCheckComplete, isAuthenticated, teamId, navigate]);

  // 保存项目上下文
  useEffect(() => {
    if (projectId && teamId) {
      saveProjectContext(projectId, teamId);
    }
  }, [projectId, teamId, saveProjectContext]);

  // 加载目录和文档数据
  useEffect(() => {
    if (!isAuthenticated || !authCheckComplete) {
      return; // 如果未认证或认证检查未完成，不进行API调用
    }
    
    if (!projectId || !teamId || teamId === 'null' || teamId === 'undefined') {
      setError('缺少项目ID或团队ID');
      setIsLoading(false);
      return;
    }

    const fetchDirectories = async () => {
      try {
        setIsLoading(true);
        setError(null);
        
        // 添加请求超时处理
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
        
        const res: ApiResponse = await api({
          url: '/doc/directory/getChildDirectoryAndDocList',
          method: 'post',
          data: {
            directoryId: '0', // 顶级目录
            projectId,
            teamId
          },
          signal: controller.signal
        });

        clearTimeout(timeoutId);

        if (res && res.success) {
          // 转换接口数据为本地数据结构
          const childDirectoryList = res.data?.childDirectoryList || [];
          const childDocumentList = res.data?.childDocumentList || [];

          const directories = childDirectoryList.map((dir: DirectoryItem) => ({
            id: dir.id,
            name: dir.name,
            type: 'folder',
            isExpanded: false,
            hasChild: dir.hasChild,
            children: []
          }));

          const documents = childDocumentList.map((doc: DocumentItem) => ({
            id: doc.docId,
            name: doc.docTitle,
            type: 'file',
            content: '# 新文档'
          }));

          setDocuments([...directories, ...documents]);
        } else {
          throw new Error(res.message || '获取目录列表失败');
        }
      } catch (err: any) {
        console.error('获取目录列表失败:', err);
        if (err.name === 'AbortError') {
          setError('请求超时，请检查网络连接');
          toast.error('请求超时，请检查网络连接');
        } else {
          setError(err.message || '获取目录列表失败');
          toast.error(err.message || '获取目录列表失败');
        }
      } finally {
        setIsLoading(false);
      }
    };

    fetchDirectories();
  }, [isAuthenticated, authCheckComplete, projectId, teamId]);
  const [selectedDoc, setSelectedDoc] = useState<DocumentNode | null>(null);
  const [content, setContent] = useState('');

  // 自动加载文档内容
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const docIdFromUrl = urlParams.get('docId');
    
    if (docIdFromUrl && documents.length > 0) {
      const doc = findNode(documents, docIdFromUrl);
      if (doc) {
        handleDocSelect(doc);
      }
    }
    setInitialLoadComplete(true);
  }, [documents]);

  // 文档切换时自动关闭编辑弹框
  useEffect(() => {
    setShowEditorModal(false);
  }, [selectedDoc?.id]);

  const handleAddDocument = async (parentId: string, type: 'folder' | 'file') => {
    if (type === 'folder') {
      setShowFolderNameModal(true);
      setNewFolderParentId(parentId); // 保存父文件夹ID
      return;
    }

    if (!projectId || !teamId) {
      toast.error('缺少项目ID或团队ID');
      return;
    }

    try {
      setIsLoading(true);
      
      // 调用新建文档接口
      const res: ApiResponse = await api({
        url: '/doc/addDoc',
        method: 'post',
        data: {
          directoryId: parentId === 'root' ? '0' : parentId,
          projectId,
          teamId,
          docTitle: '默认文档.md'
        }
      });

      if (res && res.success) {
        const newDoc: DocumentNode = {
          id: res.data?.docId || Date.now().toString(),
          name: res.data?.docTitle || '默认文档.md',
          type: 'file',
          content: '# 新文档'
        };

        const updateDocuments = (nodes: DocumentNode[]): DocumentNode[] => {
          if (parentId === 'root') {
            // 将新文件夹添加到开头，然后按类型排序（文件夹在前，文档在后）
            const allNodes = [newDoc, ...nodes];
            return allNodes.sort((a, b) => {
              if (a.type === 'folder' && b.type === 'file') return -1;
              if (a.type === 'file' && b.type === 'folder') return 1;
              return 0;
            });
          }
          
          return nodes.map(node => {
            if (node.id === parentId) {
              // 将新文件夹添加到子节点开头，然后按类型排序
              const allChildren = [newDoc, ...(node.children || [])];
              const sortedChildren = allChildren.sort((a, b) => {
                if (a.type === 'folder' && b.type === 'file') return -1;
                if (a.type === 'file' && b.type === 'folder') return 1;
                return 0;
              });
              
              return {
                ...node,
                isExpanded: true,
                children: sortedChildren
              };
            }
            if (node.children) {
              return {
                ...node,
                children: updateDocuments(node.children)
              };
            }
            return node;
          });
        };

        setDocuments(updateDocuments(documents));
        toast.success(`文档创建成功`);
        localStorage.setItem('currentDocId', res.data?.docId || '');
        newDocIdRef.current = newDoc.id; // 保存新建文档id
        await handleDocSelect(newDoc);
        // 不再直接 setShowEditorModal(true)
      } else {
        throw new Error(res.message || '创建文档失败');
      }
    } catch (error: any) {
      console.error('创建文档失败:', error);
      toast.error(error.message || '创建文档失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateFolder = async (name: string, parentId: string) => {
    if (!name.trim()) {
      toast.error('请输入目录名称');
      return;
    }

    const urlParams = new URLSearchParams(window.location.search);
    let teamId = urlParams.get('teamId') || currentTeam;
    
    if (!teamId) {
      toast.error('无法获取团队ID，请返回团队页面重新进入');
      return;
    }

    try {
      const res: ApiResponse = await api({
        url: '/doc/directory/addDirectory',
        method: 'post',
        data: {
          name,
          pid: parentId === 'root' ? '0' : parentId,
          projectId: projectId,
          teamId: teamId
        }
      });

      if (res && res.success) {
        const newFolder: DocumentNode = {
          id: res.data.id,
          name: res.data.name,
          type: 'folder',
          isExpanded: false,
          children: []
        };

        const updateDocuments = (nodes: DocumentNode[]): DocumentNode[] => {
          if (parentId === 'root') {
            // 将新文件夹添加到开头，然后按类型排序（文件夹在前，文档在后）
            const allNodes = [newFolder, ...nodes];
            return allNodes.sort((a, b) => {
              if (a.type === 'folder' && b.type === 'file') return -1;
              if (a.type === 'file' && b.type === 'folder') return 1;
              return 0;
            });
          }
          
          return nodes.map(node => {
            if (node.id === parentId) {
              // 将新文件夹添加到子节点开头，然后按类型排序
              const allChildren = [newFolder, ...(node.children || [])];
              const sortedChildren = allChildren.sort((a, b) => {
                if (a.type === 'folder' && b.type === 'file') return -1;
                if (a.type === 'file' && b.type === 'folder') return 1;
                return 0;
              });
              
              return {
                ...node,
                isExpanded: true,
                children: sortedChildren
              };
            }
            if (node.children) {
              return {
                ...node,
                children: updateDocuments(node.children)
              };
            }
            return node;
          });
        };

        setDocuments(updateDocuments(documents));
        toast.success('目录创建成功');
        setShowFolderNameModal(false);
        setNewFolderName('');
      } else {
        toast.error(res.message || '创建目录失败');
      }
    } catch (error: any) {
      console.error('创建目录失败:', error);
      toast.error(error.message || '创建目录失败');
    }
  };

  const handleDocSelect = async (doc: DocumentNode) => {
    try {
      setIsLoading(true);
      const res: ApiResponse = await api({
        url: '/doc/getDocByDocId',
        method: 'post',
        data: { docId: doc.id },
        timeout: 5000
      });
      
      if (res && res.success && res.data) {
        setSelectedDoc({
          ...doc,
          content: res.data.docContent || '# 无内容',
          createUser: res.data.createUser,
          createTime: res.data.createTime,
          updateUser: res.data.updateUser,
          updateTime: res.data.updateTime,
        });
        setContent(res.data.docContent || '# 无内容');
        localStorage.setItem('currentDocId', doc.id);
      } else {
        throw new Error(res?.message || '获取文档详情失败');
      }
    } catch (error: any) {
      console.error('获取文档详情失败:', error);
      toast.error(error.message || '获取文档详情失败');
      setSelectedDoc(doc);
      setContent(doc.content || '# 无内容');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSaveContent = async () => {
    if (!selectedDoc || !selectedDoc.id) return;

    try {
      setIsSaving(true);
      // 确保使用最新的 content 状态
      const currentContent = content;
      
      console.log('ProjectDetail 保存文档:', {
        docId: selectedDoc.id,
        docTitle: selectedDoc.name,
        docContent: currentContent,
        contentLength: currentContent.length
      });

      const res: ApiResponse = await api({
        url: '/doc/editDoc',
        method: 'post',
        data: {
          docId: selectedDoc.id,
          docTitle: selectedDoc.name,
          docContent: currentContent,
          docIcon: 'fa-solid fa-file-lines'
        },
        timeout: 10000
      });

      if (res && res.success) {
        const updateContent = (nodes: DocumentNode[]): DocumentNode[] => {
          return nodes.map(node => {
            if (node.id === selectedDoc.id) {
              return {
                ...node,
                content: currentContent
              };
            }
            if (node.children) {
              return {
                ...node,
                children: updateContent(node.children)
              };
            }
            return node;
          });
        };

        setDocuments(updateContent(documents));
        toast.success('文档已保存');
      } else {
        throw new Error(res?.message || '保存失败');
      }
    } catch (error: any) {
      console.error('保存文档失败:', error);
      toast.error(error.message || '保存文档失败');
    } finally {
      setIsSaving(false);
    }
  };

  const [expandedFolders, setExpandedFolders] = useState<Record<string, boolean>>({});

  const handleFolderClick = async (nodeId: string, currentExpanded: boolean) => {
    // 获取节点信息
    const node = findNode(documents, nodeId);
    if (!node || node.type !== 'folder') return;

    // 如果是要展开文件夹，且还没有加载过子目录数据
    if (!currentExpanded && node.hasChild && (!node.children || node.children.length === 0)) {
      try {
        setIsLoading(true);
        const res: ApiResponse = await api({
          url: '/doc/directory/getChildDirectoryAndDocList',
          method: 'post',
          data: {
            directoryId: nodeId,
            projectId: projectId,
            teamId: teamId
          }
        });

        if (res && res.success) {
          const childDirectoryList = res.data?.childDirectoryList || [];
          const childDocumentList = res.data?.childDocumentList || [];

          // 转换目录数据
          const directories = childDirectoryList.map((dir: DirectoryItem) => ({
            id: dir.id,
            name: dir.name,
            type: 'folder',
            isExpanded: false,
            hasChild: dir.hasChild,
            children: []
          }));

          // 转换文档数据
          const docs = childDocumentList.map((doc: DocumentItem) => ({
            id: doc.docId,
            name: doc.docTitle,
            type: 'file',
            content: '# 新文档'
          }));

          // 合并目录和文档，保持原有顺序
          const children = [...directories, ...docs].sort((a, b) => {
            // 目录排在前面
            if (a.type === 'folder' && b.type !== 'folder') return -1;
            if (a.type !== 'folder' && b.type === 'folder') return 1;
            return 0;
          });

          // 更新树形结构，添加子节点并设置展开状态
          const updatedDocuments = addChildrenToNode(documents, nodeId, children);
          const finalDocuments = updateNodeProperty(updatedDocuments, nodeId, 'isExpanded', true);
          setDocuments(finalDocuments);
          
          // 自动选中第一个文档（如果有）
          if (docs.length > 0) {
            handleDocSelect(docs[0]);
          }
        } else {
          throw new Error(res.message || '获取子目录失败');
        }
      } catch (error: any) {
        console.error('获取子目录失败:', error);
        toast.error(error.message || '获取子目录失败');
      } finally {
        setIsLoading(false);
      }
    } else {
      // 如果只是切换展开状态（收起或展开已加载的文件夹），直接更新状态
      const updateNode = (nodes: DocumentNode[], targetId: string): DocumentNode[] => {
        return nodes.map(node => {
          if (node.id === targetId) {
            // 切换当前节点的展开状态
            const newExpanded = !currentExpanded;
            
            // 如果是要收起，则递归收起所有子目录
            const newChildren = newExpanded 
              ? node.children 
              : node.children?.map(child => ({
                  ...child,
                  isExpanded: false,
                  children: child.children ? collapseAll(child.children) : []
                }));
                
            return {
              ...node,
              isExpanded: newExpanded,
              children: newChildren
            };
          }
          
          // 递归处理子节点
          if (node.children) {
            return {
              ...node,
              children: updateNode(node.children, targetId)
            };
          }
          
          return node;
        });
      };

      // 辅助函数：递归收起所有子目录
      const collapseAll = (nodes: DocumentNode[]): DocumentNode[] => {
        return nodes.map(node => {
          if (node.type === 'folder') {
            return {
              ...node,
              isExpanded: false,
              children: node.children ? collapseAll(node.children) : []
            };
          }
          return node;
        });
      };

      setDocuments(prev => updateNode(prev, nodeId));
    }
  };

  // 辅助函数：查找节点
  const findNode = (nodes: DocumentNode[], id: string): DocumentNode | null => {
    for (const node of nodes) {
      if (node.id === id) return node;
      if (node.children) {
        const found = findNode(node.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  // 辅助函数：为节点添加子节点
  const addChildrenToNode = (nodes: DocumentNode[], parentId: string, children: DocumentNode[]): DocumentNode[] => {
    return nodes.map(node => {
      if (node.id === parentId) {
        return {
          ...node,
          children: [...children]
        };
      }
      if (node.children) {
        return {
          ...node,
          children: addChildrenToNode(node.children, parentId, children)
        };
      }
      return node;
    });
  };

  const renderDocumentTree = (nodes: DocumentNode[], depth = 0) => {
    return (
      <div className="space-y-1">
        {nodes.map(node => (
            <div 
              className="relative group" 
              key={node.id}
              onMouseEnter={() => setHoveredNodeId(node.id)}
              onMouseLeave={() => {
                // 延迟清除悬停状态，避免子目录展开时立即清除
                setTimeout(() => {
                  setHoveredNodeId(prev => prev === node.id ? '' : prev);
                }, 100);
              }}
            >
              <motion.div
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={(e) => {
                  e.stopPropagation();
                  if (node.type === 'folder') {
                    handleFolderClick(node.id, node.isExpanded || false);
                  } else {
                    handleDocSelect(node);
                    setContent(node.content || '# 新文档');
                  }
                }}
                className={cn(
                  "flex items-center px-3 py-2 rounded-md cursor-pointer transition-colors",
                  selectedDoc?.id === node.id 
                    ? (isDark ? "bg-blue-900" : "bg-blue-100")
                    : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                )}
                style={{ paddingLeft: `${depth * 12 + 12}px` }}
              >
              <div className="flex items-center flex-1 min-w-0">
                <div className="flex items-center w-6 justify-center">
                  {node.type === 'folder' && node.hasChild && (
                    <motion.i 
                      className={cn(
                        "fa-solid fa-chevron-right text-xs",
                        isDark ? "text-blue-300" : "text-orange-400",
                        node.isExpanded && "transform rotate-90"
                      )}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ duration: 0.2 }}
                    ></motion.i>
                  )}
                </div>
                  <motion.i 
                    className={cn(
                      node.type === 'folder' ? "fa-solid fa-folder" : "fa-solid fa-file-lines",
                      "w-5 text-center",
                      isDark ? "text-blue-400" : "text-orange-500",
                      node.type === 'folder' && !node.hasChild && "opacity-70"
                    )}
                    whileTap={{
                      rotate: 15
                    }}
                    transition={{
                      type: "spring",
                      stiffness: 300,
                      damping: 10
                    }}
                  ></motion.i>
                <span className="font-mono flex-1 ml-2 break-words">{node.name}</span>

                {node.type === 'folder' && hoveredNodeId === node.id && (
                  <motion.div className="flex space-x-1 opacity-100 transition-opacity">
                    <motion.button
                      onClick={(e) => {
                        e.stopPropagation();
                        const rect = e.currentTarget.getBoundingClientRect();
                        setContextMenu({
                          visible: true,
                          x: rect.left,
                          y: rect.bottom + 5,
                          type: 'folder',
                          nodeId: node.id,
                          nodeName: node.name
                        });
                      }}
                      className={cn(
                        "w-6 h-6 rounded-full flex items-center justify-center context-menu-trigger",
                        isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                      )}
                      title="更多操作"
                      whileHover={{ scale: 1.1 }}
                      whileTap={{ scale: 0.9 }}
                    >
                      <i className="fa-solid fa-ellipsis text-xs"></i>
                    </motion.button>
                  </motion.div>
                )}

                {node.type === 'file' && hoveredNodeId === node.id && (
                  <motion.div className="flex space-x-1 opacity-100 transition-opacity">
                    <motion.button
                      onClick={(e) => {
                        e.stopPropagation();
                        const rect = e.currentTarget.getBoundingClientRect();
                        setContextMenu({
                          visible: true,
                          x: rect.left,
                          y: rect.bottom + 5,
                          type: 'file',
                          nodeId: node.id,
                          nodeName: node.name
                        });
                      }}
                      className={cn(
                        "w-6 h-6 rounded-full flex items-center justify-center context-menu-trigger",
                        isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                      )}
                      title="更多操作"
                      whileHover={{ scale: 1.1 }}
                      whileTap={{ scale: 0.9 }}
                    >
                      <i className="fa-solid fa-ellipsis text-xs"></i>
                    </motion.button>
                  </motion.div>
                )}
              </div>
              </motion.div>
            
            {node.type === 'folder' && node.isExpanded && node.children && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                transition={{ duration: 0.2 }}
                className="overflow-hidden"
              >
                {renderDocumentTree(node.children, depth + 1)}
              </motion.div>
            )}
          </div>
        ))}
      </div>
    );
  };

  // 辅助函数：更新节点属性
  const updateNodeProperty = (
    nodes: DocumentNode[], 
    id: string, 
    property: keyof DocumentNode, 
    value: any
  ): DocumentNode[] => {
    return nodes.map(node => {
      if (node.id === id) {
        return { ...node, [property]: value };
      }
      if (node.children) {
        return {
          ...node,
          children: updateNodeProperty(node.children, id, property, value)
        };
      }
      return node;
    });
  };

  // 打开编辑弹框
  const handleOpenEditor = () => {
    if (!selectedDoc) return;
    
    setCurrentEditingDocId(selectedDoc.id);
    setShowEditorModal(true);
  };

  // 关闭编辑弹框
  const handleCloseEditor = () => {
    setShowEditorModal(false);
    setCurrentEditingDocId('');
  };

  // 编辑弹框保存和版本逻辑
  const handleEditorBeforeClose = async () => {
    // 这里无需实现，交由 EditorModal 内部处理
  };

  // 编辑保存成功处理
  const handleEditorSaveSuccess = () => {
    // 重新加载文档数据以获取最新内容
    if (projectId && teamId) {
      // 触发重新加载
      setIsLoading(true);
      setError(null);
      
      const reloadData = async () => {
        try {
          const res: ApiResponse = await api({
            url: '/doc/directory/getChildDirectoryAndDocList',
            method: 'post',
            data: {
              directoryId: '0',
              projectId,
              teamId
            }
          });

          if (res && res.success) {
            const childDirectoryList = res.data?.childDirectoryList || [];
            const childDocumentList = res.data?.childDocumentList || [];

            const directories = childDirectoryList.map((dir: DirectoryItem) => ({
              id: dir.id,
              name: dir.name,
              type: 'folder',
              isExpanded: false,
              hasChild: dir.hasChild,
              children: []
            }));

            const documents = childDocumentList.map((doc: DocumentItem) => ({
              id: doc.docId,
              name: doc.docTitle,
              type: 'file',
              content: '# 新文档'
            }));

            setDocuments([...directories, ...documents]);
            
            // 重新获取当前选中文档的最新内容
            if (selectedDoc && selectedDoc.id) {
              try {
                const docRes: ApiResponse = await api({
                  url: '/doc/getDocByDocId',
                  method: 'post',
                  data: { docId: selectedDoc.id },
                  timeout: 5000
                });
                
                if (docRes && docRes.success && docRes.data) {
                  setSelectedDoc({
                    ...selectedDoc,
                    content: docRes.data.docContent || '# 无内容'
                  });
                  setContent(docRes.data.docContent || '# 无内容');
                }
              } catch (error: any) {
                console.error('重新获取文档内容失败:', error);
              }
            }
          }
        } catch (error: any) {
          console.error('重新加载数据失败:', error);
          setError(error.message || '重新加载数据失败');
        } finally {
          setIsLoading(false);
        }
      };

      reloadData();
    }
  };

  // 处理导出操作
  const handleExportAction = (type: ExportType, docId?: string, directoryId?: string, directoryName?: string) => {
    setExportType(type);
    setExportDocId(docId || '');
    setExportDirectoryId(directoryId || '');
    setExportDirectoryName(directoryName || '');
    setShowExportModal(true);
  };

  // 处理项目导出（显示目录选择）
  const handleProjectExport = () => {
    setShowDirectorySelectModal(true);
  };

  // 处理上下文菜单操作
  const handleContextMenuAction = (action: string) => {
    const { type, nodeId, nodeName } = contextMenu;
    
    switch (action) {
      case 'newDoc':
        handleAddDocument(nodeId, 'file');
        break;
      case 'newFolder':
        handleAddDocument(nodeId, 'folder');
        break;
      case 'editFolder':
        // TODO: 实现编辑目录功能
        console.log('编辑目录:', nodeName);
        break;
      case 'deleteFolder':
        // 删除目录
        handleDeleteDirectory(nodeId, nodeName);
        break;
      case 'editDoc':
        // 打开编辑弹框
        setCurrentEditingDocId(nodeId);
        setShowEditorModal(true);
        break;
      case 'copyDoc':
        // 复制文档
        handleCopyDocument(nodeId);
        break;
      case 'deleteDoc':
        // 删除文档
        handleDeleteDocument(nodeId);
        break;
      case 'exportDoc':
        // 导出单个文档
        handleExportAction(ExportType.SINGLE, nodeId);
        break;
      case 'versionHistory':
        // 打开历史版本弹窗
        setCurrentVersionDocId(nodeId);
        setShowVersionHistoryModal(true);
        break;
      case 'shareDoc':
        // 打开文档分享弹窗
        setShareType('doc');
        setShareId(nodeId);
        setShareTitle(nodeName);
        setShowShareModal(true);
        break;
      case 'exportDirectory':
        // 导出目录及子目录
        handleExportAction(ExportType.DIRECTORY, undefined, nodeId, nodeName);
        break;
      case 'exportCurrentDirectory':
        // 导出当前目录
        handleExportAction(ExportType.CURRENT_DIRECTORY, undefined, nodeId, nodeName);
        break;
    }
    
    setContextMenu(prev => ({ ...prev, visible: false }));
  };

  // 关闭上下文菜单
  const closeContextMenu = () => {
    setContextMenu(prev => ({ ...prev, visible: false }));
  };

  // 复制文档
  const handleCopyDocument = async (docId: string) => {
    try {
      // 首先获取原文档的内容
      const docRes: ApiResponse = await api({
        url: '/doc/getDocByDocId',
        method: 'post',
        data: { docId },
        timeout: 5000
      });

      if (!docRes || !docRes.success || !docRes.data) {
        throw new Error('获取原文档内容失败');
      }

      const originalDoc = docRes.data;
      const originalTitle = originalDoc.docTitle || '未命名文档';
      const newTitle = originalTitle.endsWith('_副本') 
        ? `${originalTitle}_副本` 
        : `${originalTitle}_副本`;

      // 找到原文档所在的目录ID
      const findParentDirectory = (nodes: DocumentNode[], targetId: string): string | null => {
        for (const node of nodes) {
          if (node.children) {
            for (const child of node.children) {
              if (child.id === targetId) {
                return node.id;
              }
            }
            const found = findParentDirectory(node.children, targetId);
            if (found) return found;
          }
        }
        return null;
      };

      const parentDirectoryId = findParentDirectory(documents, docId) || '0';

      // 调用新建文档接口
      const res: ApiResponse = await api({
        url: '/doc/addDoc',
        method: 'post',
        data: {
          directoryId: parentDirectoryId,
          projectId,
          teamId,
          docTitle: newTitle,
          docContent: originalDoc.docContent || '# 新文档'
        }
      });

      if (res && res.success) {
        // 刷新当前目录下的文档信息
        const refreshDirectory = async () => {
          try {
            const refreshRes: ApiResponse = await api({
              url: '/doc/directory/getChildDirectoryAndDocList',
              method: 'post',
              data: {
                directoryId: parentDirectoryId,
                projectId,
                teamId
              }
            });

            if (refreshRes && refreshRes.success) {
              const childDirectoryList = refreshRes.data?.childDirectoryList || [];
              const childDocumentList = refreshRes.data?.childDocumentList || [];

              // 转换目录数据
              const directories = childDirectoryList.map((dir: DirectoryItem) => ({
                id: dir.id,
                name: dir.name,
                type: 'folder' as const,
                isExpanded: false,
                hasChild: dir.hasChild,
                children: []
              }));

              // 转换文档数据
              const documents = childDocumentList.map((doc: DocumentItem) => ({
                id: doc.docId,
                name: doc.docTitle,
                type: 'file' as const,
                content: '# 新文档'
              }));

              // 合并目录和文档，保持原有顺序
              const children = [...directories, ...documents].sort((a, b) => {
                // 目录排在前面
                if (a.type === 'folder' && b.type !== 'folder') return -1;
                if (a.type !== 'folder' && b.type === 'folder') return 1;
                return 0;
              });

              // 更新文档列表，只更新指定目录的子节点，保持其他目录不变
              setDocuments(prev => {
                const updateDocuments = (nodes: DocumentNode[]): DocumentNode[] => {
                  return nodes.map(node => {
                    if (node.id === parentDirectoryId) {
                      // 只更新当前目录的子节点，保持展开状态
                      return {
                        ...node,
                        children: children
                      };
                    }
                    if (node.children) {
                      return {
                        ...node,
                        children: updateDocuments(node.children)
                      };
                    }
                    return node;
                  });
                };
                return updateDocuments(prev);
              });
            }
          } catch (error: any) {
            console.error('刷新目录数据失败:', error);
          }
        };

        refreshDirectory();
        toast.success('文档复制成功');
      } else {
        throw new Error(res?.message || '复制文档失败');
      }
    } catch (error: any) {
      console.error('复制文档失败:', error);
      toast.error(`复制文档失败: ${error.message || '未知错误'}`);
    }
  };

  // 删除文档
  const handleDeleteDocument = async (docId: string) => {
    try {
      const res: ApiResponse = await api({
        url: '/doc/deleteDoc',
        method: 'post',
        data: { docId },
        timeout: 5000
      });

      if (res && res.success) {
        // 从文档列表中移除被删除的文档
        setDocuments(prev => {
          const removeDoc = (nodes: DocumentNode[]): DocumentNode[] => {
            return nodes.filter(node => {
              if (node.id === docId) {
                return false; // 删除匹配的文档
              }
              if (node.children) {
                node.children = removeDoc(node.children);
              }
              return true;
            });
          };
          return removeDoc(prev);
        });

        // 如果删除的是当前选中的文档，清空选中状态
        if (selectedDoc?.id === docId) {
          setSelectedDoc(null);
          setContent('');
        }

        // 显示成功提示
        toast.success('文档删除成功');
      } else {
        throw new Error(res?.message || '删除文档失败');
      }
    } catch (error: any) {
      console.error('删除文档失败:', error);
      toast.error(`删除文档失败: ${error.message || '未知错误'}`);
    }
  };

  // 删除目录
  const handleDeleteDirectory = async (directoryId: string, directoryName: string) => {
    console.log('开始显示确认对话框'); // 调试信息
    
    // 确认删除提示
    const confirmed = await showConfirm(
      '删除目录',
      `确定要删除目录 "${directoryName}" 吗？\n\n⚠️ 警告：此操作将删除该目录下的所有子目录和文档，且无法恢复！`,
      {
        type: 'danger',
        confirmText: '删除',
        cancelText: '取消'
      }
    );

    console.log('确认对话框结果:', confirmed); // 调试信息

    if (!confirmed) {
      console.log('用户取消删除，函数返回'); // 调试信息
      return;
    }

    console.log('开始删除目录:', directoryId); // 调试信息

    try {
      const res: ApiResponse = await api({
        url: '/doc/directory/deleteDirectory',
        method: 'post',
        data: { directoryId },
        timeout: 5000
      });

      console.log('删除接口响应:', res); // 调试信息

      if (res && res.success) {
        // 从文档列表中移除被删除的目录及其所有子项
        setDocuments(prev => {
          const removeDirectory = (nodes: DocumentNode[]): DocumentNode[] => {
            return nodes.filter(node => {
              if (node.id === directoryId) {
                return false; // 删除匹配的目录
              }
              if (node.children) {
                node.children = removeDirectory(node.children);
              }
              return true;
            });
          };
          return removeDirectory(prev);
        });

        // 如果删除的目录包含当前选中的文档，清空选中状态
        const isSelectedDocInDeletedDir = (nodes: DocumentNode[], targetId: string): boolean => {
          for (const node of nodes) {
            if (node.id === targetId) {
              return true;
            }
            if (node.children && isSelectedDocInDeletedDir(node.children, targetId)) {
              return true;
            }
          }
          return false;
        };

        if (selectedDoc && isSelectedDocInDeletedDir(documents, selectedDoc.id)) {
          setSelectedDoc(null);
          setContent('');
        }

        // 显示成功提示
        toast.success(`目录 "${directoryName}" 删除成功`);
        console.log('目录删除成功'); // 调试信息
      } else {
        throw new Error(res?.message || '删除目录失败');
      }
    } catch (error: any) {
      console.error('删除目录失败:', error);
      toast.error(`删除目录失败: ${error.message || '未知错误'}`);
    }
  };

  // 监听全局点击事件，关闭上下文菜单
  useEffect(() => {
    const handleGlobalClick = (e: MouseEvent) => {
      if (contextMenu.visible) {
        const target = e.target as Element;
        if (!target.closest('.context-menu-trigger') && !target.closest('.context-menu')) {
          closeContextMenu();
        }
      }
    };

    document.addEventListener('click', handleGlobalClick);
    return () => {
      document.removeEventListener('click', handleGlobalClick);
    };
  }, [contextMenu.visible]);

  // 导出为PDF
  const handleExport = useCallback(async () => {
    if (isExporting) return;
    
    try {
      setIsExporting(true);
      toast.info("正在生成PDF...");
      
      // 尝试获取预览元素
      const previewElement = document.querySelector('.prose') || document.querySelector('[data-preview]');
      
      if (!previewElement) {
        toast.error('无法找到预览内容，请先选择或创建文档');
        return;
      }
      
      const canvas = await html2canvas(previewElement as HTMLElement, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
        logging: false,
        backgroundColor: isDark ? "#1f2937" : "#ffffff"
      });
      
      const pdf = new jsPDF({
        orientation: "portrait",
        unit: "mm"
      });
      
      const imgData = canvas.toDataURL("image/png");
      const imgWidth = 210;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      
      pdf.addImage(imgData, "PNG", 0, 0, imgWidth, imgHeight);
      pdf.save("markdown-export.pdf");
      
      toast.success("PDF导出成功");
    } catch (error) {
      console.error("导出失败:", error);
      toast.error("PDF导出失败");
    } finally {
      setIsExporting(false);
    }
  }, [isDark, isExporting]);

  // 目录创建方法
  const createDirectory = async (name: string, parentId: string | null) => {
    const res: ApiResponse = await api({
      url: '/doc/directory/addDirectory',
      method: 'post',
      data: {
        name,
        pid: parentId || '0',
        projectId,
        teamId
      }
    });
    if (res && res.success && res.data?.id) {
      return res.data.id;
    } else {
      throw new Error(res.message || '创建目录失败');
    }
  };

  // 文档创建方法
  const createDoc = async (name: string, content: string, parentId: string | null) => {
    const res: ApiResponse = await api({
      url: '/doc/addDoc',
      method: 'post',
      data: {
        docTitle: name,
        docContent: content,
        directoryId: parentId || '0',
        projectId,
        teamId
      }
    });
    if (!(res && res.success)) {
      throw new Error(res.message || '创建文档失败');
    }
  };

  useEffect(() => {
    if (newDocIdRef.current && selectedDoc && selectedDoc.id === newDocIdRef.current) {
      setCurrentEditingDocId(selectedDoc.id);
      setShowEditorModal(true);
      newDocIdRef.current = null;
    }
  }, [selectedDoc]);

  return (
    <div className={cn(
      "h-screen flex flex-col bg-transparent",
      isDark ? "text-gray-100 bg-black" : "text-gray-900 bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60"
    )}>
      {/* 导航栏 - 固定在顶部 */}
      <header className={cn(
        "flex-shrink-0 p-2 border-b backdrop-blur-md bg-opacity-90 relative z-50",
        isDark ? "bg-gray-800/90 border-gray-700" : "bg-white/90 border-gray-200"
      )}>
        <div className="container mx-auto flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <button 
              onClick={() => navigate(-1)}
              className={cn(
                "px-3 py-1 rounded-md font-mono flex items-center",
                isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
              )}
            >
              <i className="fa-solid fa-arrow-left mr-2"></i>
              返回
            </button>
            <h1 className="font-mono font-bold text-xl">项目文档</h1>
          </div>
          
          <div className="flex items-center space-x-4">
            {/* 字体选择器 */}
            <div className="flex items-center space-x-2">
              <label className={cn(
                "text-sm font-medium",
                isDark ? "text-gray-300" : "text-gray-700"
              )}>
                字体:
              </label>
              <select
                value={selectedFont}
                onChange={(e) => setSelectedFont(e.target.value)}
                className={cn(
                  "px-2 py-1 rounded-md border text-sm transition-colors",
                  isDark 
                    ? "bg-gray-700 border-gray-600 text-gray-300 hover:bg-gray-600" 
                    : "bg-white border-gray-300 text-gray-700 hover:bg-gray-50"
                )}
              >
                {fontOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
            
            {!isReadOnly && (
              <button
                onClick={handleOpenEditor}
                disabled={!selectedDoc}
                className={cn(
                  "px-4 py-2 rounded-md font-medium transition-colors",
                  selectedDoc 
                    ? (isDark ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'bg-orange-500 hover:bg-orange-600 text-white')
                    : "opacity-50 cursor-not-allowed bg-gray-400 text-white"
                )}
              >
                <i className="fa-solid fa-pen-to-square mr-2"></i>编辑
              </button>
            )}

            {/* 主题切换按钮 */}
            <button 
              onClick={toggleTheme}
              className={cn(
                "w-10 h-10 rounded-full flex items-center justify-center",
                isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
              )}
            >
              <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
            </button>

            {/* 用户菜单 */}
            {isAuthenticated && (
              <div className="relative group">
                <button className="flex items-center space-x-2">
                  <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                    <i className="fa-solid fa-user text-gray-600 dark:text-gray-300"></i>
                  </div>
                </button>
                <div className="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 invisible group-hover:visible transition-all z-[60]">
                  <div className="py-1">
                    <div className="px-4 py-2 text-sm text-gray-700 dark:text-gray-200">
                      {userInfo?.userName || '用户'}
                    </div>
                    <button 
                      onClick={logout}
                      className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                    >
                      <i className="fa-solid fa-right-from-bracket mr-2"></i>
                      退登
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* 功能菜单下拉框 */}
            <div className="relative group">
              <button 
                className={cn(
                  "w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200",
                  isDark ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
                )}
                title="更多功能"
              >
                <i className="fa-solid fa-ellipsis-vertical"></i>
              </button>
              <div className="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 invisible group-hover:visible transition-all z-[60]">
                <div className="py-1">
                  {/* 导出文档 - 只在选择文档时显示 */}
                  {selectedDoc && (
                    <button 
                      onClick={() => {
                        handleExportAction(ExportType.SINGLE, selectedDoc.id);
                      }}
                      className={cn(
                        "w-full text-left px-4 py-2 text-sm flex items-center transition-colors",
                        isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100"
                      )}
                    >
                      <i className="fa-solid fa-download mr-3 w-4"></i>
                      导出文档
                    </button>
                  )}
                  
                  {/* 项目导出 - 始终显示 */}
                  <button 
                    onClick={handleProjectExport}
                    className={cn(
                      "w-full text-left px-4 py-2 text-sm flex items-center transition-colors",
                      isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100"
                    )}
                  >
                    <i className="fa-solid fa-folder-tree mr-3 w-4"></i>
                    项目导出
                  </button>
                  
                  {/* 分享项目 - 始终显示 */}
                  <button 
                    onClick={() => {
                      setShareType('project');
                      setShareId(projectId);
                      setShareTitle(projectName);
                      setShowShareModal(true);
                    }}
                    className={cn(
                      "w-full text-left px-4 py-2 text-sm flex items-center transition-colors",
                      isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100"
                    )}
                  >
                    <i className="fa-solid fa-share mr-3 w-4"></i>
                    分享项目
                  </button>
                  
                  {/* 新增：导入按钮 */}
                  {!isReadOnly && (
                    <button
                      onClick={() => setShowPostmanImportModal(true)}
                      className={cn(
                        "w-full text-left px-4 py-2 text-sm flex items-center transition-colors",
                        isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100"
                      )}
                    >
                      <i className="fa-solid fa-file-import mr-3 w-4"></i>
                      导入
                    </button>
                  )}
                  
                  {/* 分隔线 - 只在有文档相关功能时显示 */}
                  {(selectedDoc) && (
                    <div className="border-t my-1 dark:border-gray-700"></div>
                  )}
                  
                  {/* 设置 - 始终显示 */}
                  <button 
                    className={cn(
                      "w-full text-left px-4 py-2 text-sm flex items-center transition-colors",
                      isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100"
                    )}
                  >
                    <i className="fa-solid fa-cog mr-3 w-4"></i>
                    设置
                  </button>
                  
                  {/* 帮助 - 始终显示 */}
                  <button 
                    className={cn(
                      "w-full text-left px-4 py-2 text-sm flex items-center transition-colors",
                      isDark ? "text-gray-200 hover:bg-gray-700" : "text-gray-700 hover:bg-gray-100"
                    )}
                  >
                    <i className="fa-solid fa-question-circle mr-3 w-4"></i>
                    帮助
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* 主内容区域 - 占据剩余高度 */}
      <main className="flex-1 flex items-start bg-transparent h-[calc(100vh-64px)] min-h-0">
        <div className="mx-auto max-w-6xl w-full flex h-full min-h-0">
          {/* 左侧文档目录 - 独立滚动 */}
          <div 
            className={cn(
              "w-80 flex-shrink-0 backdrop-blur-md overflow-hidden rounded-xl shadow-md h-full min-h-0",
              isDark ? "bg-gray-800/90" : "bg-white/90"
            )}
            style={{ minWidth: '280px' }}
            ref={leftPanelRef}
          >
            <div className="h-full overflow-y-auto min-h-0">
              <div className="p-4">
                <div className="flex justify-between items-center mb-4">
                  <h2 className="font-mono font-bold">文档目录</h2>
                  {isLoading ? (
                    <i className="fa-solid fa-spinner fa-spin"></i>
                  ) : error ? (
                    <button 
                      onClick={() => window.location.reload()}
                      className="text-sm text-red-500 hover:underline"
                    >
                      重试
                    </button>
                  ) : (
                    <div className="flex space-x-1">
                      {(isOwner || isRW) && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleAddDocument('root', 'file');
                          }}
                          className={cn(
                            "w-8 h-8 rounded-full flex items-center justify-center",
                            isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                          )}
                          title="添加文档"
                        >
                          <i className="fa-solid fa-file"></i>
                        </button>
                      )}
                      {(isOwner || isRW) && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleAddDocument('root', 'folder');
                          }}
                          className={cn(
                            "w-8 h-8 rounded-full flex items-center justify-center",
                            isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                          )}
                          title="添加文件夹"
                        >
                          <i className="fa-solid fa-folder-plus"></i>
                        </button>
                      )}
                    </div>
                  )}
                </div>
                {isLoading ? (
                  <div className="flex items-center justify-center h-32">
                    <i className="fa-solid fa-spinner fa-spin text-xl mr-2"></i>
                    <span>加载中...</span>
                  </div>
                ) : error ? (
                  <div className="text-red-500 p-4 text-center">
                    <p>{error}</p>
                    <button 
                      onClick={() => window.location.reload()}
                      className="mt-2 px-3 py-1 rounded-md text-sm bg-gray-200 hover:bg-gray-300"
                    >
                      重试
                    </button>
                  </div>
                ) : documents.length === 0 ? (
                  <div className="text-gray-500 p-4 text-center">
                    <p>暂无文档</p>
                  </div>
                ) : (
                  renderDocumentTree(documents)
                )}
              </div>
            </div>
          </div>

          {/* 分界线 */}
          <div 
            className={cn(
              "w-1.5 cursor-col-resize flex-shrink-0 rounded bg-gray-300 dark:bg-gray-700 transition-colors duration-200",
              "hover:bg-blue-400 dark:hover:bg-blue-500"
            )}
            style={{ minHeight: '480px', margin: '0 0' }}
            onMouseDown={(e) => {
              e.preventDefault();
              const startX = e.clientX;
              const startLeftWidth = leftPanelRef.current?.clientWidth || 320;
              const containerWidth = leftPanelRef.current?.parentElement?.clientWidth || 1200;
              
              const handleMouseMove = (moveEvent: MouseEvent) => {
                const dx = moveEvent.clientX - startX;
                const newLeftWidth = Math.max(280, Math.min(600, startLeftWidth + dx));
                
                // 确保右侧面板有足够的最小宽度
                const availableWidth = containerWidth - newLeftWidth - 6; // 6px for divider
                const newRightWidth = Math.max(300, availableWidth);
                
                if (leftPanelRef.current) {
                  leftPanelRef.current.style.width = `${newLeftWidth}px`;
                }
                if (rightPanelRef.current) {
                  rightPanelRef.current.style.minWidth = `${newRightWidth}px`;
                  rightPanelRef.current.style.width = `${newRightWidth}px`;
                }
              };

              const handleMouseUp = () => {
                document.removeEventListener('mousemove', handleMouseMove);
                document.removeEventListener('mouseup', handleMouseUp);
              };

              document.addEventListener('mousemove', handleMouseMove);
              document.addEventListener('mouseup', handleMouseUp);
            }}
          />

          {/* 右侧文档预览区 - 居中卡片美化 */}
          <div className="flex-1 flex items-start min-w-[300px] h-full min-h-0" ref={rightPanelRef}>
            {selectedDoc ? (
              <div className="flex flex-col h-full w-full">
                {/* 文档操作栏 - 固定在顶部 */}
                <div className={cn(
                  "flex-shrink-0 flex justify-between items-center p-2 border-b backdrop-blur-md rounded-t-xl",
                  isDark ? "bg-gray-800/90 border-gray-700" : "bg-white/90 border-gray-200"
                )}>
                  <div>
                    <h3 className="font-mono text-lg font-bold">{selectedDoc.name}</h3>
                    {/* 文档元信息 */}
                    <div className="text-xs text-gray-500 mt-1 flex flex-wrap gap-x-4 gap-y-1">
                      <span>创建人：{selectedDoc.createUser || '-'}</span>
                      <span>创建时间：{selectedDoc.createTime ? new Date(selectedDoc.createTime).toLocaleString('zh-CN') : '-'}</span>
                      {selectedDoc.updateUser && (
                        <span>更新人：{selectedDoc.updateUser}</span>
                      )}
                      {selectedDoc.updateTime && (
                        <span>最后更新时间：{new Date(selectedDoc.updateTime).toLocaleString('zh-CN')}</span>
                      )}
                    </div>
                  </div>
                </div>
                {/* 文档预览区域 - 卡片美化 */}
                <div className={cn(
                  "flex-1 h-full overflow-y-auto rounded-b-xl min-h-0",
                  isDark ? "bg-gray-900/80" : "bg-white/90"
                )}>
                  <div className="p-6 max-w-3xl mx-auto">
                    {initialLoadComplete ? (
                      <MilkdownPreview 
                        content={content || "请编辑文档内容"}
                        isDark={isDark}
                        className="text-base"
                        selectedFont={selectedFont}
                        data-preview="true"
                      />
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <i className="fa-solid fa-spinner fa-spin text-2xl mr-2"></i>
                        <span>加载文档内容中...</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <div className={cn(
                "flex items-center justify-center h-full w-full rounded-xl shadow-lg p-8 backdrop-blur-md",
                isDark ? "bg-gray-900/80" : "bg-white/90"
              )}>
                <p className="text-gray-500">请选择或创建文档</p>
              </div>
            )}
          </div>
        </div>
      </main>

      {/* 新建文件夹弹框 */}
      {showFolderNameModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className={cn(
            "p-6 rounded-lg shadow-lg",
            isDark ? "bg-gray-800" : "bg-white"
          )}>
            <h3 className="text-lg font-bold mb-4">新建文件夹</h3>
            <input
              type="text"
              value={newFolderName}
              onChange={(e) => setNewFolderName(e.target.value)}
              className={cn(
                "w-full p-2 border rounded mb-4",
                isDark ? "bg-gray-700 border-gray-600" : "bg-white border-gray-300"
              )}
              placeholder="文件夹名称"
            />
            <div className="flex justify-end space-x-2">
              <button
                onClick={() => setShowFolderNameModal(false)}
                className={cn(
                  "px-4 py-2 rounded",
                  isDark ? "bg-gray-600 hover:bg-gray-500" : "bg-gray-200 hover:bg-gray-300"
                )}
              >
                取消
              </button>
              <button
                onClick={() => handleCreateFolder(newFolderName, newFolderParentId)}
                className={cn(
                  "px-4 py-2 rounded text-white",
                  isDark ? "bg-blue-600 hover:bg-blue-700" : "bg-orange-500 hover:bg-orange-600"
                )}
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 编辑弹框 */}
      <EditorModal
        isOpen={showEditorModal}
        onClose={handleCloseEditor}
        docId={currentEditingDocId}
        onSaveSuccess={handleEditorSaveSuccess}
      />

      {/* 上下文菜单 */}
      {contextMenu.visible && (
        <>
          {/* 背景遮罩，点击关闭菜单 */}
          <div 
            className="fixed inset-0 z-40" 
            onClick={closeContextMenu}
          />
          
          {/* 菜单内容 */}
          <div 
            className={cn(
              "fixed z-50 py-2 rounded-lg shadow-lg border backdrop-blur-md context-menu",
              isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
            )}
            style={{
              left: contextMenu.x,
              top: contextMenu.y,
              minWidth: '160px'
            }}
          >
            {contextMenu.type === 'folder' ? (
              <>
                {(isOwner || isRW) && (
                  <button
                    onClick={() => {
                      setShowRenameModal(true);
                      setRenameTarget({ type: 'folder', id: contextMenu.nodeId, oldName: contextMenu.nodeName });
                      setRenameValue(contextMenu.nodeName);
                      closeContextMenu();
                    }}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-pen mr-3 w-4"></i>
                    重命名
                  </button>
                )}
                {(isOwner || isRW) && (
                  <button
                    onClick={() => handleContextMenuAction('newDoc')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-file mr-3 w-4"></i>
                    新建文档
                  </button>
                )}
                {(isOwner || isRW) && (
                  <button
                    onClick={() => handleContextMenuAction('newFolder')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-folder-plus mr-3 w-4"></i>
                    添加目录
                  </button>
                )}
                <div className="border-t my-1 dark:border-gray-700"></div>
                <button
                  onClick={() => handleContextMenuAction('exportDirectory')}
                  className={cn(
                    "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                    isDark ? "text-gray-200" : "text-gray-700"
                  )}
                >
                  <i className="fa-solid fa-download mr-3 w-4"></i>
                  导出目录及子目录
                </button>
                <button
                  onClick={() => handleContextMenuAction('exportCurrentDirectory')}
                  className={cn(
                    "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                    isDark ? "text-gray-200" : "text-gray-700"
                  )}
                >
                  <i className="fa-solid fa-download mr-3 w-4"></i>
                  导出当前目录
                </button>
                <div className="border-t my-1 dark:border-gray-700"></div>
                {/* 只读时不显示编辑/删除目录 */}
                {!isReadOnly && <>
                  <button
                    onClick={() => handleContextMenuAction('editFolder')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-edit mr-3 w-4"></i>
                    编辑目录
                  </button>
                  <button
                    onClick={() => handleContextMenuAction('deleteFolder')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-trash mr-3 w-4"></i>
                    删除目录
                  </button>
                </>}
              </>
            ) : (
              <>
                {(isOwner || isRW) && (
                  <button
                    onClick={() => {
                      setShowRenameModal(true);
                      setRenameTarget({ type: 'file', id: contextMenu.nodeId, oldName: contextMenu.nodeName });
                      setRenameValue(contextMenu.nodeName);
                      closeContextMenu();
                    }}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-pen mr-3 w-4"></i>
                    重命名
                  </button>
                )}
                {(isOwner || isRW) && (
                  <button
                    onClick={() => handleContextMenuAction('editDoc')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-edit mr-3 w-4"></i>
                    编辑文档
                  </button>
                )}
                {(isOwner || isRW) && (
                  <button
                    onClick={() => handleContextMenuAction('copyDoc')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-copy mr-3 w-4"></i>
                    复制
                  </button>
                )}
                <button
                  onClick={() => handleContextMenuAction('exportDoc')}
                  className={cn(
                    "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                    isDark ? "text-gray-200" : "text-gray-700"
                  )}
                >
                  <i className="fa-solid fa-download mr-3 w-4"></i>
                  导出文档
                </button>
                <button
                  onClick={() => handleContextMenuAction('versionHistory')}
                  className={cn(
                    "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                    isDark ? "text-gray-200" : "text-gray-700"
                  )}
                >
                  <i className="fa-solid fa-history mr-3 w-4"></i>
                  历史版本
                </button>
                <button
                  onClick={() => handleContextMenuAction('shareDoc')}
                  className={cn(
                    "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                    isDark ? "text-gray-200" : "text-gray-700"
                  )}
                >
                  <i className="fa-solid fa-share mr-3 w-4"></i>
                  文档分享
                </button>
                <div className="border-t my-1 dark:border-gray-700"></div>
                {/* 只读时不显示删除文档 */}
                {!isReadOnly && (
                  <button
                    onClick={() => handleContextMenuAction('deleteDoc')}
                    className={cn(
                      "w-full px-4 py-2 text-left text-sm flex items-center hover:bg-gray-100 dark:hover:bg-gray-700",
                      isDark ? "text-gray-200" : "text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-trash mr-3 w-4"></i>
                    删除文档
                  </button>
                )}
              </>
            )}
          </div>
        </>
      )}

      {/* 导出弹框 */}
      <ExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        exportType={exportType}
        teamId={teamId || undefined}
        projectId={projectId}
        directoryId={exportDirectoryId}
        docId={exportDocId}
        projectName={projectName}
        directoryName={exportDirectoryName}
        docTitle={exportDocId ? findNode(documents, exportDocId)?.name : undefined}
      />

      {/* 目录选择弹框 */}
      <DirectorySelectModal
        isOpen={showDirectorySelectModal}
        onClose={() => setShowDirectorySelectModal(false)}
        directories={documents}
        onExport={handleExportAction}
        projectName={projectName}
        currentSelectedDocId={selectedDoc?.id}
        teamId={teamId || undefined}
        projectId={projectId}
      />

      {/* Postman 导入弹窗 */}
      <PostmanImportModal
        isOpen={showPostmanImportModal}
        onClose={() => setShowPostmanImportModal(false)}
        onSuccess={() => {
          // 刷新目录
          if (projectId && teamId) {
            // 复用 fetchDirectories 逻辑
            (async () => {
              try {
                setIsLoading(true);
                setError(null);
                const res: ApiResponse = await api({
                  url: '/doc/directory/getChildDirectoryAndDocList',
                  method: 'post',
                  data: {
                    directoryId: '0',
                    projectId,
                    teamId
                  }
                });
                if (res && res.success) {
                  const childDirectoryList = res.data?.childDirectoryList || [];
                  const childDocumentList = res.data?.childDocumentList || [];
                  const directories = childDirectoryList.map((dir: any) => ({
                    id: dir.id,
                    name: dir.name,
                    type: 'folder',
                    isExpanded: false,
                    hasChild: dir.hasChild,
                    children: []
                  }));
                  const documents = childDocumentList.map((doc: any) => ({
                    id: doc.docId,
                    name: doc.docTitle,
                    type: 'file',
                    content: '# 新文档'
                  }));
                  setDocuments([...directories, ...documents]);
                }
              } catch (err: any) {
                setError(err.message || '获取目录列表失败');
              } finally {
                setIsLoading(false);
              }
            })();
          }
        }}
        projectId={projectId as string}
        teamId={teamId as string}
        parentId={undefined}
        createDirectory={createDirectory}
        createDoc={createDoc}
      />

      {/* 历史版本弹窗 */}
      <VersionHistoryModal
        isOpen={showVersionHistoryModal}
        onClose={() => setShowVersionHistoryModal(false)}
        docId={currentVersionDocId}
        docTitle={findNode(documents, currentVersionDocId)?.name || ''}
        onVersionRestored={() => {
          // 版本恢复后刷新文档内容
          if (selectedDoc && selectedDoc.id === currentVersionDocId) {
            handleDocSelect(selectedDoc);
          }
        }}
      />

      {/* 新增重命名弹窗 */}
      {showRenameModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className={cn(
            "p-6 rounded-lg shadow-lg w-80",
            isDark ? "bg-gray-800" : "bg-white"
          )}>
            <h3 className="text-lg font-bold mb-4">重命名{renameTarget.type === 'folder' ? '文件夹' : '文档'}</h3>
            <input
              type="text"
              value={renameValue}
              onChange={e => setRenameValue(e.target.value)}
              className={cn(
                "w-full p-2 border rounded mb-4",
                isDark ? "bg-gray-700 border-gray-600" : "bg-white border-gray-300"
              )}
              placeholder="新名称"
              autoFocus
            />
            <div className="flex justify-end space-x-2">
              <button
                onClick={() => setShowRenameModal(false)}
                className={cn(
                  "px-4 py-2 rounded",
                  isDark ? "bg-gray-600 hover:bg-gray-500" : "bg-gray-200 hover:bg-gray-300"
                )}
              >
                取消
              </button>
              <button
                onClick={async () => {
                  if (!renameValue.trim()) return;
                  setIsRenaming(true);
                  try {
                    if (renameTarget.type === 'folder') {
                      // 目录重命名
                      const res: ApiResponse = await api({
                        url: '/doc/directory/renameDirectory',
                        method: 'post',
                        data: { id: renameTarget.id, name: renameValue.trim() },
                      });
                      if (!res.success) throw new Error(res.message || '重命名失败');
                    } else {
                      // 文档重命名
                      const res: ApiResponse = await api({
                        url: '/doc/renameDoc',
                        method: 'post',
                        data: { docId: renameTarget.id, docTitle: renameValue.trim() },
                      });
                      if (!res.success) throw new Error(res.message || '重命名失败');
                    }
                    toast.success('重命名成功');
                    // 刷新目录树
                    if (projectId && teamId) {
                      const res: ApiResponse = await api({
                        url: '/doc/directory/getChildDirectoryAndDocList',
                        method: 'post',
                        data: { directoryId: '0', projectId, teamId }
                      });
                      if (res && res.success) {
                        const childDirectoryList = res.data?.childDirectoryList || [];
                        const childDocumentList = res.data?.childDocumentList || [];
                        const directories = childDirectoryList.map((dir: DirectoryItem) => ({
                          id: dir.id,
                          name: dir.name,
                          type: 'folder',
                          isExpanded: false,
                          hasChild: dir.hasChild,
                          children: []
                        }));
                        const documents = childDocumentList.map((doc: DocumentItem) => ({
                          id: doc.docId,
                          name: doc.docTitle,
                          type: 'file',
                          content: '# 新文档'
                        }));
                        setDocuments([...directories, ...documents]);
                      }
                    }
                    setShowRenameModal(false);
                  } catch (err: any) {
                    toast.error(err.message || '重命名失败');
                  } finally {
                    setIsRenaming(false);
                  }
                }}
                disabled={isRenaming || !renameValue.trim()}
                className={cn(
                  "px-4 py-2 rounded text-white",
                  isRenaming
                    ? "opacity-50 cursor-not-allowed bg-gray-400"
                    : isDark ? "bg-blue-600 hover:bg-blue-700" : "bg-orange-500 hover:bg-orange-600"
                )}
              >
                {isRenaming ? '重命名中...' : '确定'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 分享弹窗 */}
      <ShareModal
        isOpen={showShareModal}
        onClose={() => setShowShareModal(false)}
        type={shareType}
        id={shareId}
        title={shareTitle}
        teamId={shareType === 'project' ? teamId : undefined}
      />
    </div>
  );
}